package com.microstation.controller.system;

import com.microstation.common.Assist;
import com.microstation.entity.po.QuesInfo;
import com.microstation.entity.po.view.UserInfoSigninView;
import com.microstation.entity.po.view.UserQuesRecView;
import com.microstation.service.QuesInfoService;
import com.microstation.service.view.UserInfoSigninViewService;
import com.microstation.service.view.UserQuesRecViewService;
import com.microstation.util.DateUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/api/outExcel")
public class OutExcelController extends BaseController {
    private final static Logger LOG = LoggerFactory.getLogger(OutExcelController.class);
    @Autowired
    private UserInfoSigninViewService userInfoSigninViewService;
    @Autowired
    private QuesInfoService quesInfoService;
    @Autowired
    private UserQuesRecViewService userQuesRecViewService;

    /**
     * 导出用户记录
     *
     * @param userInfoSigninView
     * @param response
     */
    @RequestMapping(value = "/outUserInfo")
    public void outUserInfo(UserInfoSigninView userInfoSigninView, HttpServletResponse response) {
        List<UserInfoSigninView> list = userInfoSigninViewService.findListByExample(userInfoSigninView);
        String[] title = {"姓名", "邀请码", "用户类型", "手机号", "报名号", "性别", "公司", "职位", "证件号", "证件类型", "邮箱", "上车点", "是否单间", "发票抬头", "税号", "分论坛", "二维码编号", "券号", "是否报名", "是否签到", "问卷"};
        try {
            this.outUserInfoProcess(title, list, response);
            //return new Result(Boolean.FALSE, ResultEnum.SUCCESS, AppConst.NULL);
        } catch (Exception e) {
            e.printStackTrace();
            //return new Result(Boolean.TRUE, ResultEnum.ERROR.getType(), e.getMessage(), AppConst.NULL);
        }
    }

    private void outUserInfoProcess(String[] title, List<UserInfoSigninView> list, HttpServletResponse response) throws IOException {
        String filename = "用户记录" + DateUtil.format(System.currentTimeMillis(), "yyyyMMddHHmmss");
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1") + ".xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        OutputStream output = response.getOutputStream();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        try {
            sheet.setDefaultColumnWidth(15);
            HSSFRow row = null;
            HSSFCell cell = null;
            row = sheet.createRow(0);
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            UserInfoSigninView item = null;
            Integer column = 0;
            for (int i = 0; i < list.size(); i++) {
                column = 0;
                item = list.get(i);
                row = sheet.createRow(i + 1);

                cell = row.createCell(column);
                cell.setCellValue(item.getName());

                cell = row.createCell(++column);
                cell.setCellValue(item.getInviteCode());

                cell = row.createCell(++column);
                String userType = "";
                if (item.getLevel() == 4) {
                    userType = "VIP 1680";
                } else if (item.getLevel() == 3) {
                    userType = "VIP 1380";
                } else if (item.getLevel() == 2) {
                    userType = "普通 880";
                } else if (item.getLevel() == 1) {
                    userType = "普通 580";
                }
                cell.setCellValue(userType);

                cell = row.createCell(++column);
                cell.setCellValue(item.getMobile());

                cell = row.createCell(++column);
                cell.setCellValue(item.getRegNumber());

                cell = row.createCell(++column);
                cell.setCellValue(item.getSex().intValue() == 1 ? "男" : "女");

                cell = row.createCell(++column);
                cell.setCellValue(item.getCompany());

                cell = row.createCell(++column);
                cell.setCellValue(item.getPosition());

                cell = row.createCell(++column);
                cell.setCellValue(item.getCredentialNo());

                cell = row.createCell(++column);
                cell.setCellValue(item.getCredentialType());

                cell = row.createCell(++column);
                cell.setCellValue(item.getEmail());

                cell = row.createCell(++column);
                cell.setCellValue(item.getAboardPoint());

                cell = row.createCell(++column);
                String isSingle = "";
                if (item.getIsSingle() != null){
                    if (item.getIsSingle().intValue() == 0){
                        isSingle = "否";
                    }else if (item.getIsSingle().intValue() == 1){
                        isSingle = "是";
                    }
                }
                cell.setCellValue(isSingle);

                cell = row.createCell(++column);
                cell.setCellValue(item.getInvoice());

                cell = row.createCell(++column);
                cell.setCellValue(item.getDutyParagraph());

                cell = row.createCell(++column);
                String forum = "";
                if (item.getForumNum() != null) {
                    if (item.getForumNum().intValue() == 1) {
                        forum = "中国智造，领航全球";
                    } else if (item.getForumNum().intValue() == 2) {
                        forum = "电商新视界";
                    } else if (item.getForumNum().intValue() == 3) {
                        forum = "玩转采购节";
                    }
                }
                cell.setCellValue(forum);

                cell = row.createCell(++column);
                cell.setCellValue(item.getQrcode());

                cell = row.createCell(++column);
                cell.setCellValue(item.getTicketNo());

                cell = row.createCell(++column);
                cell.setCellValue(item.getRegFlag() == 1 ? "已报名" : "未报名");

                cell = row.createCell(++column);
                cell.setCellValue(item.getSignCount() >= 1 ? "已签到" : "未签到");

                cell = row.createCell(++column);
                cell.setCellValue(item.getQuesCount() >= 1 ? "已作答" : "未作答");
            }
            workbook.write(output);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            output.flush();
            output.close();
            workbook.close();
        }
    }

    /**
     * 问卷记录
     *
     * @param userInfoSigninView
     * @param response
     */
    @PostMapping(value = "/outUserQues")
    public void outUserQues(UserInfoSigninView userInfoSigninView, HttpServletResponse response) {
        userInfoSigninView.setQuesCount(1L);
        List<UserInfoSigninView> userlist = userInfoSigninViewService.findListByExample(userInfoSigninView);
        Assist assist = new Assist();
        QuesInfo queryQuesParam = new QuesInfo();
        queryQuesParam.setDelFlag(1);
        queryQuesParam.setActId(userInfoSigninView.getActId());
        assist.setOrder(Assist.order("seq", true));
        List<QuesInfo> quesList = new ArrayList<QuesInfo>();
        try {
            QuesInfo first = new QuesInfo();
            first.setName("姓名/题目");
            quesList.add(first);
            quesList.addAll(quesInfoService.findList(queryQuesParam, assist));
            this.outUserQuesRecProcess(quesList, userlist, response);
            //return new Result(Boolean.FALSE, ResultEnum.SUCCESS, AppConst.NULL);
        } catch (Exception e) {
            e.printStackTrace();
            //return new Result(Boolean.TRUE, ResultEnum.ERROR.getType(), e.getMessage(), AppConst.NULL);
        }
    }

    private void outUserQuesRecProcess(List<QuesInfo> quesList, List<UserInfoSigninView> userlist, HttpServletResponse response) throws IOException {
        String filename = "问卷记录" + DateUtil.format(System.currentTimeMillis(), "yyyyMMddHHmmss");
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1") + ".xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        OutputStream output = response.getOutputStream();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        try {
            HSSFRow row = null;
            HSSFCell cell = null;
            row = sheet.createRow(0);
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setWrapText(true);
            for (int i = 0; i < quesList.size(); i++) {
                cell = row.createCell(i);
                cell.setCellValue(quesList.get(i).getName());
                cell.setCellStyle(cellStyle);
                sheet.autoSizeColumn(i, true);
            }

            UserInfoSigninView userInfoSigninView = null;
            List<UserQuesRecView> userQuesRecViewList = null;
            UserQuesRecView queryParam = null, item = null;
            Assist assist = null;

            for (int i = 0; i < userlist.size(); i++) {
                userInfoSigninView = userlist.get(i);
                row = sheet.createRow(i + 1);
                cell = row.createCell(0);
                cell.setCellValue(userInfoSigninView.getName());
                queryParam = new UserQuesRecView();
                assist = new Assist();
                queryParam.setUserId(userInfoSigninView.getId());
                queryParam.setActId(userInfoSigninView.getActId());
                assist.setOrder(Assist.order("seq", true));
                userQuesRecViewList = userQuesRecViewService.findList(queryParam, assist);
                int size = userQuesRecViewList.size();
                for (int j = 0; j < size; j++) {
                    item = userQuesRecViewList.get(j);
                    cell = row.createCell(j + 1);
                    cell.setCellValue(item.getAnswer());
                }
            }
            workbook.write(output);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            output.flush();
            output.close();
            workbook.close();
        }
    }

    /**
     * 导出题目/选项人数
     *
     * @param quesInfo
     * @param response
     */
    @PostMapping(value = "/outQuesCount")
    public void outQuesCount(QuesInfo quesInfo, HttpServletResponse response) {
        try {
            Assist assist = new Assist();
            assist.setOrder(Assist.order("seq", true));
            List<QuesInfo> quesInfoList = quesInfoService.findList(quesInfo, assist);
            String[] title = {"题目/选项", "是", "否", "1星", "2星", "3星", "4星", "5星"};
            this.outQuesCountProcess(title, quesInfoList, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void outQuesCountProcess(String[] title, List<QuesInfo> quesInfoList, HttpServletResponse response) throws IOException {
        String filename = "问卷项人数统计" + DateUtil.format(System.currentTimeMillis(), "yyyyMMddHHmmss");
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1") + ".xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        OutputStream output = response.getOutputStream();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        try {
            sheet.setDefaultColumnWidth(15);
            HSSFRow row = null;
            HSSFCell cell = null;
            row = sheet.createRow(0);
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }

            int size = quesInfoList.size();
            QuesInfo quesInfo = null;
            UserQuesRecView queryCount = null;
            for (int i = 0; i < size; i++) {
                quesInfo = quesInfoList.get(i);
                row = sheet.createRow(i + 1);
                cell = row.createCell(0);
                cell.setCellValue(quesInfo.getName());
                for (int j = 0; j < 7; j++) {
                    queryCount = new UserQuesRecView();
                    queryCount.setId(quesInfo.getId());
                    queryCount.setActId(quesInfo.getActId());
                    cell = row.createCell(j + 1);
                    if (j == 0) {
                        queryCount.setAnswer("是");
                        cell.setCellValue(userQuesRecViewService.count(queryCount));
                    } else if (j == 1) {
                        queryCount.setAnswer("否");
                        cell.setCellValue(userQuesRecViewService.count(queryCount));
                    } else {
                        queryCount.setAnswer(String.valueOf(j - 1));
                        cell.setCellValue(userQuesRecViewService.count(queryCount));
                    }
                }
            }
            workbook.write(output);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            output.flush();
            output.close();
            workbook.close();
        }
    }
}
